import { defineStore } from "pinia";
import type { User, LoginForm, RegisterForm, UserState } from "@/types";
import { AuthAPI } from "@/api/auth";

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    user: null,
    isLoggedIn: false,
    token: null,
    bookshelf: [],
    readingHistory: [],
    readerSettings: {
      fontSize: 16,
      lineHeight: 1.6,
      backgroundColor: "#ffffff",
      textColor: "#333333",
      fontFamily: "system-ui",
      pageWidth: 800,
      nightMode: false,
    },
    walletPassword: null,
    paymentRecords: [],
  }),

  getters: {
    isAdmin: (state) => state.user?.username === "admin",
    isModerator: (state) => state.user?.username === "admin",
    isVip: (state) => state.user?.is_vip === true,
    isActive: (state) => true,
    canManageUsers: (state) => state.user?.username === "admin",
  },

  actions: {
    // 初始化用户状态
    async initUser() {
      try {
        const result = await AuthAPI.checkAuthStatus();

        if (result.success && result.user) {
          this.user = result.user;
          this.token = localStorage.getItem("novel_app_token");
          this.isLoggedIn = true;
        } else {
          this.user = null;
          this.token = null;
          this.isLoggedIn = false;
        }
      } catch (error) {
        console.error("初始化用户状态失败:", error);
        this.user = null;
        this.token = null;
        this.isLoggedIn = false;
      }
    },

    // 用户登录
    async login(loginForm: LoginForm) {
      try {
        const result = await AuthAPI.login(loginForm);

        if (result.success) {
          this.user = result.user || null;
          this.token = result.token || null;
          this.isLoggedIn = true;
          return { success: true, message: result.message };
        } else {
          return { success: false, message: result.message };
        }
      } catch (error) {
        const message = (error as Error).message || "登录失败";
        return { success: false, message };
      }
    },

    // 用户注册
    async register(registerForm: RegisterForm) {
      try {
        const result = await AuthAPI.register(registerForm);

        if (result.success) {
          this.user = result.user || null;
          this.token = result.token || null;
          this.isLoggedIn = true;
          return { success: true, message: result.message };
        } else {
          return { success: false, message: result.message };
        }
      } catch (error) {
        const message = (error as Error).message || "注册失败";
        return { success: false, message };
      }
    },

    // 用户退出
    async logout() {
      try {
        await AuthAPI.logout();
      } catch (error) {
        console.error("退出登录失败:", error);
      } finally {
        this.user = null;
        this.token = null;
        this.isLoggedIn = false;
        this.bookshelf = [];
      }
    },

    // 更新阅读器设置
    updateReaderSettings(settings: Partial<typeof this.readerSettings>) {
      this.readerSettings = { ...this.readerSettings, ...settings };
      localStorage.setItem("novel_app_reader_settings", JSON.stringify(this.readerSettings));
    },

    // 加载阅读器设置
    loadReaderSettings() {
      try {
        const stored = localStorage.getItem("novel_app_reader_settings");
        if (stored) {
          this.readerSettings = { ...this.readerSettings, ...JSON.parse(stored) };
        }
      } catch (error) {
        console.error("加载阅读器设置失败:", error);
      }
    },
  },
});
